package com.vcredit.bird.monitor;

import java.lang.reflect.Method;
import java.net.SocketTimeoutException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.vcredit.creditcat.exception.BirdRequestFailException;

/**
 * 默认异常监控处理类,要增加新的异常继承该类或实现MonitorExceptionHandle接口,加上MonitorAdvice注解
 * 
 * @author chengchao01
 *
 */
@Component("defaultExceptionHandler")
public class DefaultExceptionHandler implements MonitorExceptionHandler {

	private static Map<String, Integer> timeOutMethodMap = new ConcurrentHashMap<String, Integer>();

	@Value("${monitor.timeout.count}")
	private int TIME_OUT_COUNT;

	@ExceptionHandler(SocketTimeoutException.class)
	public Message SocketTimeoutExceptionHandle(String methodDesc, Exception e, Method method) {
		Message message = null;
		if (!(e instanceof SocketTimeoutException)) {
			return null;
		}
		int time = timeOutMethodMap.get(method.getName()) == null ? 0 : timeOutMethodMap.get(method.getName());
		if (time == (TIME_OUT_COUNT - 1)) {
			timeOutMethodMap.put(method.getName(), 0);
			message = new Message("系统异常警告", methodDesc + "超时" + TIME_OUT_COUNT + "次");
		} else {
			timeOutMethodMap.put(method.getName(), ++time);
		}
		return message;
	}

	@ExceptionHandler(BirdRequestFailException.class)
	public Message BirdRequestFailExceptionHandle(String methodDesc, Exception e, Method method) {
		Message message = null;
		if (!(e instanceof BirdRequestFailException)) {
			return null;
		}
		message = new Message("系统异常警告", methodDesc + "请求失败");
		return message;
	}
}
